import React, { useEffect, useState } from 'react';
import { FlatList, SafeAreaView, ActivityIndicator, Text, useColorScheme } from 'react-native';
import SearchNoteCard from './SearchNoteCard.tsx';

// 定义列表项的类型
interface NoteItem {
  noteId: number;
  imageUrl: string;
  title: string;
  content: string;
  authorAvatarUrl: string;
  authorId: string;
  viewCount: number;
}

// 定义查询参数的类型
interface QueryParams {
  author: string;
  content: string;
  navigation: any; // 添加 navigation 属性
}

// 数据获取函数
const fetchData = async ({ author, content }: QueryParams): Promise<NoteItem[] | null> => {
  const url = `http://10.128.128.188:4523/m2/6361734-6057711-default/294823794?author=${author}&content=${content}`;
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('网络响应失败');
    }
    const data: NoteItem[] = await response.json();
    return data;
  } catch (error) {
    console.error('获取数据时出错:', error);
    return null;
  }
};

const SearchNoteCardItemList: React.FC<QueryParams> = ({ author, content, navigation }) => {
  const colorScheme = useColorScheme();
  const isDarkMode = colorScheme === 'dark';
  // 用于存储获取到的笔记数据
  const [notes, setNotes] = useState<NoteItem[]>([]);
  // 用于表示数据是否正在加载
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    const fetchNotes = async () => {
      setIsLoading(true);
      const result = await fetchData({ author, content });
      if (result) {
        setNotes(result);
      }
      setIsLoading(false);
    };

    if (content) {
      fetchNotes();
    } else {
      setNotes([]);
      setIsLoading(false);
    }
  }, [author, content]);

  const renderItem = ({ item }: { item: NoteItem }) => (
    <SearchNoteCard
      noteId={item.noteId}
      imageUrl={item.imageUrl}
      title={item.title}
      content={item.content}
      authorAvatarUrl={item.authorAvatarUrl}
      authorId={item.authorId}
      viewCount={item.viewCount}
      navigation={navigation}
    />
  );

  if (isLoading) {
    return (
      <SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: isDarkMode ? '#121212' : '#fff' }}>
        <ActivityIndicator size="large" color="#0000ff" />
      </SafeAreaView>
    );
  }

  if (notes.length === 0) {
    return (
      <SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: isDarkMode ? '#121212' : '#fff' }}>
        <Text style={{ color: isDarkMode ? '#fff' : '#000' }}>未找到相关结果</Text>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={{ backgroundColor: isDarkMode ? '#121212' : '#fff' }}>
      <FlatList
        data={notes}
        renderItem={renderItem}
        keyExtractor={(item, index) => index.toString()}
      />
    </SafeAreaView>
  );
};

export default SearchNoteCardItemList;
